<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Sales\Validator;

use Admin\Entity\Delivery;
use Laminas\Validator\AbstractValidator;

class ShipOneOrderDeliveryValidator extends AbstractValidator
{
    const NOT_SCALAR    = 'notScalar';
    const DELIVERY_ERROR   = 'deliveryError';

    protected $messageTemplates = [
        self::NOT_SCALAR        => "这不是一个标准输入值",
        self::DELIVERY_ERROR    => "部分选中的快递信息不可用"
    ];

    private $entityManager;

    public function __construct($options = null)
    {
        if(isset($options['entityManager'])) $this->entityManager = $options['entityManager'];

        parent::__construct($options);
    }

    public function isValid($value)
    {
        $isValid = true;

        if (!is_array($value) && !empty($value)) {
            $this->error(self::NOT_SCALAR);
            return false;
        }

        foreach ($value as $item) {
            if(empty($item) || intval($item) <= 0) {
                $this->error(self::DELIVERY_ERROR);
                return false;
            }
            $deliveryInfo = $this->entityManager->getRepository(Delivery::class)->findOneBy(['deliveryId' => $item, 'deliveryState' => 1]);
            if($deliveryInfo == null) {
                $this->error(self::DELIVERY_ERROR);
                return false;
            }
        }

        return $isValid;
    }
}